use std::sync::Arc;

use ntex::web::types::{Json, Path, State};
use sqlx::Row;
use crate::{errors::CustomError, models::{comment::Comment, user::{Admin, GetHubUserInfo, User}}, AppState};





//通过文章 id 获取文章的所有评论 - 包括发表评论的用户信息
pub async fn get_comments_for_article_id(
    article_id: Path<(u32,)>,
    state: State<Arc<AppState>>,
) -> Result<Json<Vec<Comment>>, CustomError> {
    let db_pool = &state.db_pool;

    let id = article_id.0;

    // 查找对应文章的所有评论
    let comments = sqlx::query(
        "SELECT comments.id, comments.user_id, comments.content, comments.created_at, users.name,
        users.avatar_url FROM comments JOIN users ON comments.user_id = users.id
        WHERE comments.articles_id = ?"
    )
    .bind(id)
    .fetch_all(db_pool)
    .await?
    .iter()
    .map(|row| Comment {
        id: row.get("id"),
        user: Some(GetHubUserInfo {
            id: row.get("user_id"),
            name: row.get("name"),
            avatar_url: row.get("avatar_url")
        }),
        articles_id: None,
        content: row.get("content"),
        created_at: row.get("created_at"),
    })
    .collect::<Vec<Comment>>();

    Ok(Json(comments))
}

//新增评论
pub async fn add_comment(
    user: User,
    comment: Json<Comment>,
    state: State<Arc<AppState>>,
) -> Result<String, CustomError> {
    let db_pool = &state.db_pool;

    let user_id = user.id;
    let article_id = match comment.articles_id {
        Some(id) => id,
        None => return Err(CustomError::BadRequest("请提供要评论的文章ID".into())),
    };

    if sqlx::query("SELECT * FROM articles WHERE id = ?")
        .bind(article_id)
        .fetch_optional(db_pool)
        .await?
        .is_none() {
            return Err(CustomError::BadRequest("要评论的文章不存在".into()));
        }

    sqlx::query("INSERT INTO comments (user_id, articles_id, content) VALUES (?, ?, ?)")
        .bind(user_id)
        .bind(article_id)
        .bind(comment.content.clone())
        .execute(db_pool)
        .await?;

    Ok("评论成功".into())
}

//删除评论 用户只能删除自己的评论 管理员可以删除任何评论
pub async fn delete_comment(
    user: User,
    admin: Option<Admin>,
    comment_id: Path<(u32,)>,
    state: State<Arc<AppState>>,
) -> Result<String, CustomError> {
    let db_pool = &state.db_pool;

    let comment_id = comment_id.0;
    let user_id = user.id;
    let is_admin = admin.is_some(); // 判断用户是否为管理员

    let rows_affected = if is_admin {
        sqlx::query("DELETE FROM comments WHERE id = ?")
            .bind(comment_id)
            .execute(db_pool)
            .await?
    } else {
        sqlx::query("DELETE FROM comments WHERE id = ? AND user_id = ?")
            .bind(comment_id)
            .bind(user_id)
            .execute(db_pool)
            .await?
    }
    .rows_affected();

    if rows_affected == 0 {
        return Err(CustomError::NotFound("删除评论失败，评论不存在或不是你的评论".into()));
    }

    Ok("删除评论成功".into())
}